<template>
  <el-dialog title="添加信息" :visible.sync="addInfoDialogVisible" @close="closeDialog" @open="openDialog">
  <el-form :model="addUserFrom" label-width="80px" :rules="rules" ref="form">
    <el-form-item label="用户名:" prop="username">
     <el-input v-model="addUserFrom.username"></el-input>
    </el-form-item>
    <el-form-item label="密码:" prop="password">
     <el-input v-model="addUserFrom.password"></el-input>
    </el-form-item>
    <el-form-item label="姓名:">
     <el-input v-model="addUserFrom.truename"></el-input>
    </el-form-item>
    <el-form-item label="手机:">
     <el-input v-model="addUserFrom.phone"></el-input>
    </el-form-item>
    <el-form-item label="地区:">
     <CityPicker :cityPickerValue.sync="addUserFrom.region" :option="3" ref="cityPicker"/>
    </el-form-item>
    <el-form-item label="是否启用:" prop="status">
          <el-radio v-model="addUserFrom.status" label="2">启用</el-radio>
          <el-radio v-model="addUserFrom.status" label="1">禁用</el-radio>
    </el-form-item>
    <!-- <el-form-item label="角色:" prop="role">
      <el-checkbox-group v-model="addUserFrom.role">
    <el-checkbox label="info">信息管理员</el-checkbox>
    <el-checkbox label="user">角色管理员</el-checkbox>
  </el-checkbox-group>
    </el-form-item> -->
    <el-form-item label="角色:" prop="role">
      <el-checkbox-group v-model="addUserFrom.role">
    <el-checkbox :label="item.role" v-for="item in userRoles.data" :key="item.role">{{item.name}}</el-checkbox>
  </el-checkbox-group>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="addInfoDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
  </div>
</el-dialog>
</template>

<script>
import { reactive, ref, watch, onBeforeMount } from '@vue/composition-api'
import CityPicker from '@/components/CityPicker'
import sha1 from 'js-sha1'
import { addUserRequest, editUserRequest, getRoleRequest } from '@/api/user'
import { emailVailtor, specialCharVaildator, passwordValidator } from '@/utils/validator.js'
export default {
  components: {
    CityPicker
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: () => {}
    }
  },
  setup (props, { emit, root, refs }) {
    // 验证邮箱
    var validateUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入用户名'))
      } else if (!emailVailtor(value)) {
        return callback(new Error('请输入合法用户名'))
      }
      callback()
    }
    var validatePassword = (rule, value, callback) => {
      value = specialCharVaildator(value)
      addUserFrom.password = value
      if (addUserFrom.id && !value) {
        return callback()
      }
      if (!value) {
        return callback(new Error('请输入密码'))
      } else if (!passwordValidator(value)) {
        return callback(new Error('请输入6位到20位的字母与数字'))
      }
      callback()
    }
    var validateStatus = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请选择状态'))
      }
      callback()
    }
    // 对话框显示与隐藏
    const addInfoDialogVisible = ref(props.visible)
    const closeDialog = () => {
      emit('close')
      resetForm()
      refs.cityPicker.reset()
    }
    const openDialog = () => {
      for (const key in props.editData) {
        if (key === 'region') continue
        if (key === 'role') {
          addUserFrom[key] = props.editData[key].split(',')
          continue
        }
        addUserFrom[key] = props.editData[key]
      }
    }
    // 但对话框的显示需要父组件的新增按钮控制 所以控制显示与隐藏要由父组件的值决定
    // 因为关闭对话框同步修改组件声明的变量addInfoDialogVisible
    // 显示时 父组件的visible改变 传递过来的props的visible改变 监听props 当props中的值改变
    // 带动该组件的ref值addInfoDialogVisible改变 当隐藏对话框时 为了同步组件addInfoDialogVisible和父组件的visible
    // 促发父组件的colse事件 改变父组件的visible
    watch(props, () => {
      addInfoDialogVisible.value = props.visible
    })
    // 表单操作
    const addUserFrom = reactive({
      username: '',
      truename: '',
      password: '',
      phone: '',
      status: '',
      role: [],
      region: {}
    })
    const loading = ref(false)
    const rules = reactive({
      username: [
        { validator: validateUsername, trigger: 'blur' }
      ],
      password: [
        { validator: validatePassword, trigger: 'blur' }
      ],
      status: [{ validator: validateStatus, trigger: 'change' }]
    })
    // 重置表单
    const resetForm = () => {
      for (const key in addUserFrom) {
        if (key === 'region') {
          addUserFrom[key] = {}
          continue
        }
        if (key === 'role') {
          addUserFrom[key] = []
          continue
        }
        addUserFrom[key] = ''
      }
    }
    // 提交表单
    const submitForm = async () => {
      refs.form.validate(async (valid) => {
        if (valid) {
          loading.value = true
          const requestParams = { ...addUserFrom }
          requestParams.role = requestParams.role.join(',')
          requestParams.region = JSON.stringify(requestParams.region)
          if (requestParams.id) {
            // 编辑
            if (requestParams.password) {
              requestParams.password = sha1(requestParams.password)
            } else {
              delete requestParams.password
            }
            const { data: res } = await editUserRequest(requestParams)
            if (res.resCode === 0) {
              root.$message({
                type: 'success',
                message: res.message
              })
              closeDialog()
            }
          } else {
            // 添加
            requestParams.password = sha1(requestParams.password)
            const { data: res } = await addUserRequest(requestParams)
            if (res.resCode === 0) {
              root.$message({
                type: 'success',
                message: res.message
              })
              closeDialog()
            }
          }

          loading.value = false
        }
      })
    }
    // 用户角色
    const userRoles = reactive({
      data: []
    })
    const getUserRoles = async () => {
      const { data: res } = await getRoleRequest()
      console.log(res)
      userRoles.data = res.data
    }
    // 生命周期
    onBeforeMount(() => {
      getUserRoles()
    })
    return {
      addInfoDialogVisible,
      closeDialog,
      submitForm,
      loading,
      addUserFrom,
      rules,
      openDialog,
      userRoles
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
